Intersection and Difference between Arrays

Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array:

sub difference {
    my ( @array1, @array2 ) = ( @{$_[0]}, @{$_[1]} );
    my @difference = (); my @intersection = 0;
    my %count = ();
    foreach my $element (@array1, @array2) { $count{$element}++ }
    foreach my $element (keys %count) {
        push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
    }
    return \@difference;
}

http://perldoc.perl.org/perlfaq4.html

Homepage
Comments

Hide Comments